<template>
  <div class="tags-edit topic-card">
    <div class="tags-edit-recommended">
      <h4 class="tags-title">推荐话题</h4>
      <div class="recommended-flex" v-if="topicsList && topicsList.length">
        <div class="pane" ref="paneRef">
          <div class="pane-title">
            <a-anchor line-less :change-hash="true" scroll-container="#containerTag">
              <a-anchor-link
                v-for="section in topicsList"
                :key="section.id"
                :href="'#' + section.id"
                @click.prevent="setActiveTag(section.type, 'sys')"
              >
                {{ section.type }}
              </a-anchor-link>
            </a-anchor>
          </div>
          <div id="containerTag" class="content" ref="scrollContainer">
            <div v-for="section in topicsList" :key="section.id" :id="section.id" class="section">
              <div class="recommended-content-name" :class="{ active: activeTagName === section.type }">
                {{ section.type }}
              </div>
              <a-space wrap>
                <span
                  v-for="(item, index) in section.talks"
                  :key="index"
                  class="tags-value"
                  :class="{ active: isActiveTag(item.name, 'sys') }"
                  @click="addTag(section, item)"
                >
                  {{ item.name }}
                </span>
              </a-space>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-data">暂无推荐话题</div>
    </div>
    <div class="tags-edit-custom">
      <h4 class="tags-title" style="margin-bottom: 10px">自定义话题</h4>
      <a-space>
        <a-input
          v-model="customInput"
          style="width: 339px"
          placeholder="请输入自定义话题"
          :max-length="30"
          show-word-limit
          @press-enter="addCustomTag"
        />
        <a-button @click="addCustomTag">添加</a-button>
      </a-space>
      <h4 class="tags-title" style="margin-top: 60px; margin-bottom: 10px">已选择话题 ({{ topicsCount }}/10)</h4>
      <div class="tags-list">
        <a-tag v-for="tag in addedTags" :key="tag.id" closable @close="removeTag(tag)">
          {{ tag.name }}
        </a-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { getTopicList } from '@/api/articleWorkBench';
  import { Message } from '@arco-design/web-vue';
  import { uuid as uuidv4 } from '@/utils/uuid';
  const emit = defineEmits(['insertTopicConfirm', 'insertTopicCancel']);

  const topicsList = ref<any[]>([]);
  const activeTagName = ref<string | null>(null);
  const customInput = ref<string>('');
  const addedTags = ref<any[]>([]);
  const sysTags = ref<any[]>([]); // 保存推荐话题
  const customTags = ref<any[]>([]); // 保存自定义话题

  const topicsCount = computed(() => addedTags.value.length);

  onMounted(async () => {
    try {
      const res = await getTopicList();
      if (res?.code === 0) {
        activeTagName.value = res.data[0]?.type;
        topicsList.value = res.data.map((tag: any, index: number) => ({ ...tag, id: 'href' + (index + 1) }));
      }
    } catch (error) {
      console.error('Error fetching content management topics:', error);
      Message.error('请求失败，请重试！');
    }
  });

  const isTagAdded = (tagValue: string, type: string) => {
    const tagsToCheck = type === 'sys' ? sysTags.value : customTags.value;
    return tagsToCheck.some((tag) => tag.name === tagValue);
  };

  const isActiveTag = (tagValue: string, type: string) => isTagAdded(tagValue, type);

  const setActiveTag = (name: string, type: string) => {
    if (type === 'sys') activeTagName.value = name;
  };

  const addTag = (section: any, item: any) => {
    if (isTagAdded(item.name, 'sys')) {
      Message.warning('该推荐话题已添加！');
      return;
    }
    if (topicsCount.value >= 10) {
      Message.warning('最多支持添加10个话题！');
      return;
    }
    const newTag = { id: uuidv4(), name: item.name, type: 'sys' };
    sysTags.value.push(newTag);
    addedTags.value.push(newTag);
  };

  const removeTag = (tagToRemove: any) => {
    const tagsToModify = tagToRemove.type === 'sys' ? sysTags : customTags;
    tagsToModify.value = tagsToModify.value.filter((tag) => tag.id !== tagToRemove.id);
    addedTags.value = addedTags.value.filter((tag) => tag.id !== tagToRemove.id);
  };

  const addCustomTag = () => {
    const inputText = customInput.value.trim();
    if (!inputText) {
      Message.warning('话题不能为空！');
      return;
    }
    if (topicsCount.value >= 10) {
      Message.warning('最多支持添加10个话题！');
      return;
    }
    if (isTagAdded(inputText, 'custom')) {
      Message.warning('该自定义话题已存在！');
      return;
    }
    const newCustomTag = { id: uuidv4(), name: inputText, type: 'custom' };
    customTags.value.push(newCustomTag);
    addedTags.value.push(newCustomTag);
    customInput.value = '';
  };

  const getSelectedTopics = () => {
    return addedTags.value;
  };

  // 导出方法
  defineExpose({
    getSelectedTopics,
  });
</script>

<style lang="less" scoped>
  .no-data {
    text-align: center;
    padding: 20px;
  }
</style>
